package br.com.kees.persistencia;

import java.util.Map;

import javax.faces.application.NavigationHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.FlushModeType;
import javax.persistence.Persistence;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class JPAUtil {
	private static final EntityManagerFactory emf =
		Persistence.createEntityManagerFactory("conexao");	
	
	protected static EntityManager em;
	
	public static EntityManager getEntityManager() {
		if (em==null || !em.isOpen()) {
			em = emf.createEntityManager();
			em.setFlushMode(FlushModeType.COMMIT);
		}
		return em;
	}
	
	public static void closeEntityManager(EntityManager em) {
		if(em != null && em.isOpen()) {
			em.close();
		}
	}
	
	public static HttpServletRequest getRequest() {
		return (HttpServletRequest) getExternalContext().getRequest();
	}
	
	public static HttpServletResponse getResponse() {
		return (HttpServletResponse) getExternalContext().getResponse();
	}
	
	public static void redirecionaPagina(String string) {
		FacesContext fc = FacesContext.getCurrentInstance();
		NavigationHandler nh = fc.getApplication().getNavigationHandler();
		nh.handleNavigation(fc, null, string);
	}
	
	public static void setSessionAttribute(String key, Object value) {
		Map<String, Object> map = getExternalContext().getSessionMap();
		map.put(key, value);
	}
	
	private static ExternalContext getExternalContext() {
		FacesContext fc = FacesContext.getCurrentInstance();
		return fc.getExternalContext();
	}

}
